package com.frontop.system.modules.user.controller;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.frontop.common.annotation.AnonymousAccess;
import com.frontop.common.domain.UserDto;
import com.frontop.common.domain.UserJurisdiction;
import com.frontop.common.util.JwtUtil;
import com.frontop.common.util.ResultJsonUtil;
import com.frontop.dubbo.api.auth.Oauth2Api;
import com.frontop.system.modules.sys.model.SysRole;
import com.frontop.system.modules.sys.model.TUserRole;
import com.frontop.system.modules.sys.service.TUserRoleService;
import com.frontop.system.modules.sys.vo.SysRoleVO;
import com.frontop.system.modules.user.model.TUser;
import com.frontop.system.modules.user.model.TUserShowInfo;
import com.frontop.system.modules.user.service.SysDictService;
import com.frontop.system.modules.user.service.TUserService;
import com.frontop.system.modules.user.vo.TUserVO;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping
public class TUserController {

    @Resource
    private SysDictService memberService;

    @Reference
    private Oauth2Api oauth2Api;

    @Autowired
    TUserService tUserService;

    @Autowired
    TUserRoleService tUserRoleService;

//    @AnonymousAccess
//    @PostMapping("/login")
//    public ResultJsonUtil<Object> login(HttpServletRequest request, @RequestBody Map<String,String> map) {
//        ResultJsonUtil<Object> res = oauth2Api.postAccessToken(map);
//        return res;
//    }

    @RequestMapping("/service")
    public String service() {
        return JSONObject.toJSONString(memberService.getDictAll());
    }

    /**
     * 返回登录用户信息
     * @param authentication
     * @return
     */
    //@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    @GetMapping(value = "/getUserInfo")
    public ResultJsonUtil<Object> getUserInfo(Authentication authentication) {
        Claims claims = JwtUtil.getJwtInfo(authentication);
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",claims.get("user_name"));
        TUser tUser = tUserService.getOne(queryWrapper);
        UserDto userDto = JSONUtil.toBean(JSONObject.toJSONString(tUser), UserDto.class);
        return new ResultJsonUtil().success(userDto);
    }

    @ApiOperation(value = "用户列表")
    @PostMapping("/selectUserPage")
    @PreAuthorize("hasAuthority('system:user:list')")
    public ResultJsonUtil<Object> selectUserPage(@RequestBody(required = false) TUserVO vo,
                                                 Authentication authentication,
                                                 HttpServletRequest request) {
        //获取当前登录用户基本权限信息

        UserJurisdiction userJurisdiction = JwtUtil.getUserJurisdiction(authentication);
        //只能查看子组织和自己组织的用户
        vo.setLowerOrganizationIds(userJurisdiction.getLowerOrganizationIds());

        Page<TUserShowInfo> page = new Page<>(vo.getPageNo(), vo.getPageSize());
        page = tUserService.selectUserPage(page,vo);
        return new ResultJsonUtil().success(page);
    }


    @ApiOperation(value = "修改自己的用户信息")
    @PostMapping("/upThisUserInfo")
    public ResultJsonUtil<Object> upThisUserInfo(@RequestBody TUser tUser, HttpServletRequest request,Authentication authentication) {
        Claims claims = JwtUtil.getJwtInfo(authentication);
        String userName = (String)claims.get("user_name");
        if(userName.equals(tUser.getUserName())){
            TUser tUserData = new TUser();
            tUserData.setName(tUser.getName());
            tUserData.setPhone(tUser.getPhone());
            tUserData.setEmail(tUser.getEmail());
            tUserData.setPost(tUser.getPost());
            tUserData.setRemark(tUser.getRemark());
            tUserData.setId(tUser.getId());
            tUserService.updateById(tUserData);
            return new ResultJsonUtil().success("请求成功");
        }else {
            return new ResultJsonUtil().customFail("只允许修改自己的用户信息");
        }
    }

    @ApiOperation(value = "添加修改用户的信息")
    @PostMapping("/addOrUpUser")
    @PreAuthorize("hasAuthority('system:user:upOrAdd')")
    @Transactional
    public ResultJsonUtil<Object> addOrUpUser(@RequestBody(required = false) TUser tUser, HttpServletRequest request) {
        if(StringUtils.isEmpty(tUser.getUserName())){
            return new ResultJsonUtil().customFail("登录名不能为空");
        }
        //验证登录名重复
        if(verificationUserNameRepeat(tUser)){
            return new ResultJsonUtil().customFail("用户名已存在，请更换其他用户名");
        }


        if(tUser.getId() != null){
            //禁止修改用户密码
            tUser.setPassword(null);
            Map<String,Object> map = new HashMap<>();
            map.put("user_id",tUser.getId());
            tUserRoleService.removeByMap(map);
        }else {
            //新增用户使用默认密码
            tUser.setPassword(oauth2Api.getEncodePassword("123456"));
            tUser.setCreateTime(new Date());
            tUser.setStatus(1);
            tUser.setHeadImage("defult.gif");
        }


        tUserService.saveOrUpdate(tUser);
        for (Integer roleId:tUser.getRoles()){
            TUserRole tUserRole = new TUserRole();
            tUserRole.setRoleId(roleId);
            tUserRole.setUserId(tUser.getId());
            tUserRoleService.save(tUserRole);
        }
        return new ResultJsonUtil().success("请求成功");
    }

    @ApiOperation(value = "营销app端注册用户")
    @PostMapping("/appRegisterUser")
    @AnonymousAccess
    public ResultJsonUtil<Object> updatePassword(@RequestBody JSONObject jsonObject,
                                                 HttpServletRequest request) {
        String userName = jsonObject.getString("userName");
        String passData = jsonObject.getString("passData");
        String phoneData = jsonObject.getString("phoneData");

        if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(userName) || StringUtils.isEmpty(phoneData)){
            return new ResultJsonUtil().customFail("注册信息不合法");
        }

        TUser tUser = new TUser();
        tUser.setUserName(userName);
        //验证登录名重复
        if(verificationUserNameRepeat(tUser)){
            return new ResultJsonUtil().customFail("用户名已存在，请更换其他用户名");
        }
        tUser.setPassword(oauth2Api.getEncodePassword(passData));
        tUser.setCreateTime(new Date());
        tUser.setStatus(1);
        tUser.setHeadImage("defult.jpg");
        tUser.setOrganization(46); //app端组织id
        tUser.setRole(7); //app端普通用户
        UUID id=UUID.randomUUID();
        String[] idd=id.toString().split("-");
        tUser.setName("用户_"+idd[1]);
        tUser.setPhone(phoneData);
        tUserService.save(tUser);
        return new ResultJsonUtil().success("注册成功");
    }

    /**
     * 验证用户名重复
     * @param tUser
     * @return
     */
    public boolean verificationUserNameRepeat(TUser tUser){
        QueryWrapper<TUser> wrapper = new QueryWrapper();
        wrapper.eq("user_name",tUser.getUserName());
        wrapper.eq("status",1);
        TUser loUser = tUserService.getOne(wrapper);

        if(loUser != null){
            if(tUser.getId() != null){
                if(!loUser.getId().equals(tUser.getId())){
                    return true;
                }
            }else {
                if(loUser.getUserName().equals(tUser.getUserName())){
                    return true;
                }
            }
        }
        return false;
    }


    @ApiOperation(value = "删除用户")
    @GetMapping("/deleteUserByUserName/{userName}")
    @PreAuthorize("hasAuthority('system:user:delete')")
    public ResultJsonUtil<Object> deleteUserByUserName(@PathVariable("userName") String userName,
                                                 Authentication authentication) {
        tUserService.deleteUserByUserName(userName);
        return new ResultJsonUtil().success("删除成功");
    }

    @ApiOperation(value = "用户个人信息")
    @GetMapping("/selectShowUserInfo")
    public ResultJsonUtil<Object> selectShowUserInfo(Authentication authentication) {
        Claims claims = JwtUtil.getJwtInfo(authentication);
        return new ResultJsonUtil().success(tUserService.selectShowUserInfo((String) claims.get("user_name")));
    }

    @ApiOperation(value = "获取用户头像")
    @GetMapping("/getUserHeader")
    public ResultJsonUtil<Object> getUserHeader(Authentication authentication) {
        Claims claims = JwtUtil.getJwtInfo(authentication);
        return new ResultJsonUtil().success(tUserService.selectShowUserInfo((String) claims.get("user_name")).getHeadImage());
    }

    @ApiOperation(value = "上传头像")
    @PostMapping("/userUploadHeadImage")
    public ResultJsonUtil<Object> userUploadHeadImage(@RequestParam("file") MultipartFile multipartFile,
                                           Authentication authentication,
                                           HttpServletRequest request) {
        Claims claims = JwtUtil.getJwtInfo(authentication);
        String userName = (String) claims.get("user_name");
        String userHead = tUserService.userUploadHeadImage(userName,multipartFile);
        return new ResultJsonUtil().success(userHead);
    }

    @ApiOperation(value = "用户修改密码")
    @PostMapping("/updatePassword")
    public ResultJsonUtil<Object> updatePassword(@RequestParam("oldPwd") String  oldPwd,
                                                      @RequestParam("newPwd") String  newPwd,
                                                      @RequestParam("repeatPwd") String  repeatPwd,
                                                      Authentication authentication,
                                                      HttpServletRequest request) {
        Claims claims = JwtUtil.getJwtInfo(authentication);
        String userName = (String) claims.get("user_name");

        return tUserService.updatePassword(oldPwd,newPwd,repeatPwd,userName);
    }


}